package com.graduation.fq.student.Process;

import com.alibaba.fastjson.JSONArray;
import com.graduation.fq.student.Utils.Const;
import com.graduation.fq.student.Utils.ScoreUrlIndex;
import com.graduation.fq.student.domain.ScoreVO;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jifang
 * Time 2016/5/27 20:15.
 */
public class ScoreProcess extends BaseProcess {

    private List<String> urls = new ArrayList<>();

    {
        urls.add("/score/score_list.do?u_id=%s");
        urls.add("/score/score_top_n.do?u_id=%s&n=%s");
        urls.add("/score/score_un_passed.do?u_id=%s");
        urls.add("/score/score_total.do?u_id=%s");
    }

    /**
     * request
     */
    private ScoreUrlIndex index;
    private int uId;
    private Integer n;

    /**
     * response
     */
    private List<ScoreVO> scores;
    private Double total;

    public ScoreProcess(ScoreUrlIndex index, int uId, Integer n) {
        this.index = index;
        this.uId = uId;
        this.n = n;
    }

    public ScoreUrlIndex getIndex() {
        return index;
    }

    public void setIndex(ScoreUrlIndex index) {
        this.index = index;
    }

    public int getuId() {
        return uId;
    }

    public void setuId(int uId) {
        this.uId = uId;
    }

    public int getN() {
        return n;
    }

    public void setN(int n) {
        this.n = n;
    }

    public List<ScoreVO> getScores() {
        return scores;
    }

    public void setScores(List<ScoreVO> scores) {
        this.scores = scores;
    }

    public Double getTotal() {
        return total;
    }

    public void setTotal(Double total) {
        this.total = total;
    }

    @Override
    String getRequestUrl() {
        String url;
        if (getIndex() == ScoreUrlIndex.SCORE_TOP_N){
            url = String.format(urls.get(getIndex().getIndex()), getuId(), getN());
        }else{
            url = String.format(urls.get(getIndex().getIndex()), getuId());
        }
        return url;
    }

    @Override
    String getParameter() {
        return null;
    }

    @Override
    void onResult(JSONObject object) {
        int status = object.optInt("status");
        setStatus(status);
        if (status == Const.HTTP_SUCCESS ) {
            if (getIndex() == ScoreUrlIndex.SCORE_TOTAL){
                setTotal(object.optDouble("data"));
            }else{
                String json = object.optJSONArray("data").toString();
                List<ScoreVO> scores = JSONArray.parseArray(json, ScoreVO.class);
                setScores(scores);
            }
        }
    }
}
